package com.xqb.modules.service.impl;

import com.xqb.common.constants.MyConstants;
import com.xqb.modules.domain.pojo.Mongo.Message;
import com.xqb.modules.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-07-01  01:07
 */
@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addMessage(Message message) {
        // MongoDB 保存消息
        mongoTemplate.save(message, MyConstants.NOTICE_COLLECTION);
    }

    /**
     * 根据用户ID 获取消息
     *
     * @param receiverIds 接收者ID列表
     * @return 消息列表
     */
    @Override
    public List<Message> getNoticeByUserIds(List<String> receiverIds) {
        // 根据用户ID获取消息，并获取前十条
        Criteria criteria = Criteria.where("receiverId").in(receiverIds)
                .and("isRead").is(false);
        Query query = new Query(criteria).limit(10);

        // 查询消息并返回结果列表
        List<Message> messageList = mongoTemplate.find(query, Message.class, MyConstants.NOTICE_COLLECTION);

        // 如果结果列表不为空，则更新已读状态为true
        if (!messageList.isEmpty()) {
            Update update = new Update().set("isRead", true);
            mongoTemplate.updateMulti(query, update, Message.class, MyConstants.NOTICE_COLLECTION);
        }

        // 返回消息列表
        return messageList;
    }

    @Override
    public List<Message> queryList(Message message) {
        // 创建Criteria对象
        Criteria criteria = new Criteria();

        Criteria criteria1 = new Criteria("receiverId").in(message.getReceiverId())
                .and("senderId").in(message.getSenderId());
        Criteria criteria2 = new Criteria("senderId").in(message.getReceiverId())
                .and("receiverId").in(message.getSenderId());

        criteria.orOperator(criteria1, criteria2);

        Query query = new Query(criteria);
        query.limit(20);
        // 直接设置为升序排列，避免后续反转列表
        query.with(Sort.by(Sort.Order.asc("time")));

        List<Message> messageList = mongoTemplate.find(query, Message.class, MyConstants.NOTICE_COLLECTION);
        return messageList;
    }
}